<% @current_tab = 'home' %>

<form id="query-form" method="POST" action="/queries">
  <div id="editor-container">
    <textarea name="query" id="query-field"><%= h(params[:q]) %></textarea>
  </div>
  <div class="form-actions">
    <input type="submit" class="btn" name="submit" value="Run" />
    <span class="deemphasized help-inline"><abbr title="Ctrl+Enter">Ctrl+&crarr;</abbr> or <abbr title="Command+Enter">&#8984;&crarr;</abbr></span>
  </div>
</form>

<div id="loading">
  <div class="alert">
    <div class="cancel-container">
      <a class="btn btn-mini btn-warning cancel">Cancel</a>
    </div>
    <span id="spinner"></span>
    Executing query...
  </div>
</div>

<div id="error" class="alert alert-error">
  <strong>Problem!</strong>
  <span class="message"></span>
</div>

<div id="results">
  <div class="alert alert-success">
    <strong>Success!</strong>
    Query returned <span class="row-count"></span> row<span class="row-count-plural">s</span>.
  </div>

  <table class="table table-condensed" id="results-table">
    <thead>
      <tr class="headers"></tr>
    </thead>
    <tbody class="results"></tbody>
  </table>
</div>

<script type="text/javascript">
  $('#loading .cancel').click(function(e) {
    e.preventDefault();
    editor.cancelQuery();
  });

  var opts = {
    lines: 11,
    length: 4,
    width: 2,
    radius: 4,
    color: '#C09853',
    speed: 1.2,
    trail: 60
  };
  var target = document.getElementById('spinner');
  var spinner = new Spinner(opts).spin(target);

  var form = $('#query-form');
  $('#results, #error, #loading').hide();
  var editor = new QueryEditor(form, {
    onQueryStart: function() {
      $('#results, #error').hide();
      $('#loading').show();
    },
    onQuerySuccess: function(query) {
      $('#loading, #error').hide();
      $('#results')
        .show()
        .find('.row-count')
          .text(query.results.length - 1)
        .end()
        .find('.row-count-plural')
          .toggle(query.results.length !== 2);

      var headerRow = $('#results .headers').empty();
      var container = $('#results .results').empty();

      for (var i = 0; i < query.results[0].length; i++) {
        headerRow.append('<th>' + query.results[0][i] + '</th>');
      }

      for (var i = 1; i < query.results.length; i++) {
        var result = query.results[i];
        var row = $('<tr></tr>');

        for (var j = 0; j < result.length; j++) {
          if (result[j]) {
            row.append($('<td></td>').text(result[j]));
          } else {
            row.append('<td class="null">null</td>');
          }
        }

        container.append(row);
      }
    },
    onQueryError: function(error) {
      $('#loading, #results').hide();
      $('#error')
        .show()
        .find('.message')
          .text(error);
    }
  });

  editor.focus();

  <% if params[:run] %>
  editor.submit();
  <% end %>
</script>
